﻿package fj.site
{
	import flash.display.MovieClip;
	import flash.events.EventDispatcher;
	import com.asual.*
	import fj.utils.FJParse;
	import fj.utils.FJAnalytics;
	import fj.events.FJEvent;

	public class FJModel extends EventDispatcher
	{
		protected static var instance:Model;

		public var root:MovieClip;
		public var arrayURL:Array;
		public var navigationMenu:MovieClip;
		public var analytics:Boolean;
		public var preload:Boolean;

		private var _deepLinking:Boolean;
		private var _conteudo:MovieClip;
		private var _pagina:String;
		private var _paginaAnterior:String;

		public function set conteudo( mc:MovieClip ):void
		{
			_conteudo = mc;
			_conteudo.addEventListener( FJEvent.OUT, conteudoOut );
		}
		public function get conteudo():MovieClip
		{
			return _conteudo;
		}
		public function set pagina( s:String ):void
		{
			var formatedPagina:String = s;
			if ( s.substr(0,1) != "/" ) {
				formatedPagina = "/" + formatedPagina;
			}
			if ( s.substr(-1,1) != "/" ) {
				formatedPagina = formatedPagina + "/";
			}
			if ( _deepLinking ) {
				SWFAddress.setValue( formatedPagina );
			} else {
				_paginaAnterior = _pagina;
				_pagina = s;
				arrayURL = FJParse.url( formatedPagina );
				if ( navigationMenu ) {
					navigationMenu.setSelected( s );
				}
				_conteudo.out();
			}
			if( analytics ){
				FJAnalytics.send( formatedPagina );
			}
		}
		public function get pagina():String
		{
			return _pagina;
		}
		public function get paginaAnterior():String
		{
			return _paginaAnterior;
		}
		public function set deepLinking( b:Boolean ):void
		{
			if ( b ) {
				SWFAddress.addEventListener( SWFAddressEvent.CHANGE, swfAddressChange );
			} else {
				SWFAddress.removeEventListener( SWFAddressEvent.CHANGE, swfAddressChange );
			}
			_deepLinking = b;
		}
		public function get deepLinking():Boolean
		{
			return _deepLinking;
		}
		private function conteudoOut( e:FJEvent ):void
		{
			root.gotoAndStop( _pagina );
		}
		private function swfAddressChange( e:SWFAddressEvent ):void
		{
			var tempValue:String;
			if ( e.value == "/" ) {
				tempValue = "/Home/";
			} else {
				tempValue = e.value;
			}
			arrayURL = FJParse.url( tempValue );
			if ( arrayURL[0] != _pagina ) {
				if ( navigationMenu ) {
					navigationMenu.selected = arrayURL[0];
				}
				conteudo.out();
			}
			_pagina = arrayURL[0];
		}
	}
}